package com.base.themvx.widget

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View

class CircularProgressBar(context: Context, attrs: AttributeSet) : View(context, attrs) {
    private var progress = 0
    private val maxProgress = 100
    private val paint = Paint().apply {
        style = Paint.Style.STROKE
        strokeWidth = 10f // 设置圆环的宽度
        isAntiAlias = true
    }
    private var gradientColors = intArrayOf(Color.RED, Color.GREEN, Color.BLUE) // 默认渐变色
    private lateinit var gradient: SweepGradient

    fun setProgress(progress: Int) {
        this.progress = progress
        invalidate() // 重绘视图
    }

    fun setGradientColors(colors: IntArray) {
        gradientColors = colors
        invalidate() // 重绘视图以应用新的渐变色
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val width = width.toFloat()
        val height = height.toFloat()
        val radius = Math.min(width, height) / 2 - paint.strokeWidth / 2
        val centerX = width / 2
        val centerY = height / 2

        // 创建渐变
        gradient = SweepGradient(centerX, centerY, gradientColors, null)
        val matrix = Matrix()
        matrix.setRotate(-90f, centerX, centerY)
        gradient.setLocalMatrix(matrix)
        paint.shader = gradient

        // 画背景圆环
        paint.color = 0xFFDDDDDD.toInt() // 灰色
        canvas.drawCircle(centerX, centerY, radius, paint)

        // 画进度圆环
        val sweepAngle = 360 * progress / maxProgress
        canvas.drawArc(centerX - radius, centerY - radius, centerX + radius, centerY + radius, -90f, sweepAngle.toFloat(), false, paint)
    }
}
